import { defineStore } from 'pinia'
import { login, logout, getUserInfo } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    username: (state) => state.userInfo.username || '',
    role: (state) => state.userInfo.role || ''
  },
  
  actions: {
    // 用户登录
    async loginAction(userInfo) {
      try {
        const { username, password } = userInfo
        const response = await login({ username, password })
        
        // 详细打印响应结构
        console.log('登录响应完整数据:', JSON.stringify(response))
        
        // 后端返回格式：{ code: 200, msg: "操作成功", data: { token: "xxx", userInfo: {...} } }
        if (response.code !== 200) {
          return Promise.reject(new Error(response.msg || '登录失败'))
        }
        
        // 从响应的data字段中提取数据 - LoginResponseDTO
        const loginResponse = response.data
        if (!loginResponse) {
          return Promise.reject(new Error('登录失败：响应数据为空'))
        }
        
        console.log('登录数据:', JSON.stringify(loginResponse))
        
        // 直接提取LoginResponseDTO中的token和userInfo
        const token = loginResponse.token
        const userData = loginResponse.userInfo
        
        if (!token) {
          console.error('无法从响应中提取token:', loginResponse)
          return Promise.reject(new Error('登录失败：无法获取token'))
        }
        
        if (!userData) {
          console.warn('无法从响应中提取用户信息，使用空对象代替')
        }
        
        console.log('提取的token:', token)
        console.log('提取的用户数据:', userData)
        
        // 存储token和用户信息
        this.token = token
        this.userInfo = userData || {}
        
        // 保存到本地存储
        localStorage.setItem('token', token)
        localStorage.setItem('userInfo', JSON.stringify(userData || {}))
        
        // 再次检查token是否已正确保存
        const savedToken = localStorage.getItem('token')
        console.log('保存后的token:', savedToken)
        
        return Promise.resolve({ token, userInfo: userData })
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 获取用户信息
    async getUserInfoAction() {
      try {
        const response = await getUserInfo()
        console.log('获取用户信息响应:', JSON.stringify(response))
        
        // 处理后端返回的标准格式
        if (response.code !== 200) {
          return Promise.reject(new Error(response.msg || '获取用户信息失败'))
        }
        
        // 从响应的data字段提取用户数据
        const userData = response.data
        if (!userData) {
          return Promise.reject(new Error('获取用户信息失败：响应数据为空'))
        }
        
        this.userInfo = userData
        localStorage.setItem('userInfo', JSON.stringify(userData))
        
        return Promise.resolve(userData)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 用户登出
    async logoutAction() {
      try {
        await logout()
        this.resetState()
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 重置状态
    resetState() {
      this.token = ''
      this.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  }
}) 